<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="theme-color" content="#0078E7"><meta name="author" content="yangbo.wang"><meta name="copyright" content="yangbo.wang"><meta name="generator" content="Hexo 5.3.0"><meta name="theme" content="hexo-theme-yun"><title>模型查询 | Blog</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@900&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-markdown-css@0.1.22/dist/yun/yun-markdown.min.css"><script src="//at.alicdn.com/t/font_1140697_ed8vp4atwoj.js" async></script><script src="https://cdn.jsdelivr.net/npm/scrollreveal/dist/scrollreveal.min.js" defer></script><script>document.addEventListener("DOMContentLoaded", () => {
  [".post-card",".post-content img"].forEach((target)=> {
    ScrollReveal().reveal(target);
  })
});
</script><link rel="shortcut icon" type="image/svg+xml" href="/yun.svg"><link rel="mask-icon" href="/yun.svg" color="#0078E7"><link rel="alternate icon" href="/yun.ico"><link rel="preload" href="/css/hexo-theme-yun.css" as="style"><link rel="preload" href="/js/utils.js" as="script"><link rel="preload" href="/js/hexo-theme-yun.js" as="script"><link rel="prefetch" href="/js/sidebar.js" as="script"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><script id="yun-config">
    const Yun = window.Yun || {};
    window.CONFIG = {"hostname":"example.com","root":"/","title":"你的月亮我的心","version":"1.4.0","mode":"dark","copycode":true,"page":{"isPost":true},"anonymous_image":"https://cdn.jsdelivr.net/gh/YunYouJun/cdn/img/avatar/none.jpg","say":{"api":"https://v1.hitokoto.cn","hitokoto":true},"fireworks":{"colors":["102, 167, 221","62, 131, 225","33, 78, 194"]}};
  </script><link rel="stylesheet" href="/css/hexo-theme-yun.css"><script src="/js/utils.js"></script><script src="/js/hexo-theme-yun.js"></script><meta name="description" content="简介 查询集表示从数据库中获取的对象集合   查询集可以含有零个、一个或多个过滤器   过滤器基于所给的参数限制查询的结果   从Sql的角度，查询集和select语句等价，过滤器像where和limit子句   接下来主要讨论如下知识点   查询集   字段查询：比较运算符，F对象，Q对象      查询集 在管理器上调用过滤器方法会返回查询集   查询集经过过滤器筛选后返回新的查询集，因此可以">
<meta property="og:type" content="article">
<meta property="og:title" content="模型查询">
<meta property="og:url" content="http://example.com/2021/01/17/django%20%E6%A8%A1%E5%9E%8B%E6%9F%A5%E8%AF%A2/index.html">
<meta property="og:site_name" content="Blog">
<meta property="og:description" content="简介 查询集表示从数据库中获取的对象集合   查询集可以含有零个、一个或多个过滤器   过滤器基于所给的参数限制查询的结果   从Sql的角度，查询集和select语句等价，过滤器像where和limit子句   接下来主要讨论如下知识点   查询集   字段查询：比较运算符，F对象，Q对象      查询集 在管理器上调用过滤器方法会返回查询集   查询集经过过滤器筛选后返回新的查询集，因此可以">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-01-17T07:12:04.120Z">
<meta property="article:modified_time" content="2021-01-17T07:28:19.634Z">
<meta property="article:author" content="yangbo.wang">
<meta property="article:tag" content="Django">
<meta property="article:tag" content="模型查询">
<meta property="article:tag" content="查询集">
<meta name="twitter:card" content="summary"><script src="/js/ui/mode.js"></script></head><body><script defer src="https://cdn.jsdelivr.net/npm/animejs@latest"></script><script defer src="/js/ui/fireworks.js"></script><canvas class="fireworks"></canvas><div class="container"><a class="sidebar-toggle hty-icon-button" id="menu-btn"><div class="hamburger hamburger--spin" type="button"><span class="hamburger-box"><span class="hamburger-inner"></span></span></div></a><div class="sidebar-toggle sidebar-overlay"></div><aside class="sidebar"><script src="/js/sidebar.js"></script><ul class="sidebar-nav"><li class="sidebar-nav-item sidebar-nav-toc hty-icon-button sidebar-nav-active" data-target="post-toc-wrap" title="Table of Contents"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-list-ordered"></use></svg></li><li class="sidebar-nav-item sidebar-nav-overview hty-icon-button" data-target="site-overview-wrap" title="Overview"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-passport-line"></use></svg></li></ul><div class="sidebar-panel" id="site-overview-wrap"><div class="site-info fix-top"><a class="site-author-avatar" href="/about/" title="yangbo.wang"><img width="96" loading="lazy" src="/Yun.png" alt="yangbo.wang"></a><div class="site-author-name"><a href="/about/">yangbo.wang</a></div><a class="site-name" href="/about/site.html">Blog</a><sub class="site-subtitle"></sub><div class="site-desciption"></div></div><nav class="site-state"><a class="site-state-item hty-icon-button icon-home" href="/" title="Home"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-home-4-line"></use></svg></span></a><div class="site-state-item"><a href="/archives/" title="Archives"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-archive-line"></use></svg></span><span class="site-state-item-count">8</span></a></div><div class="site-state-item"><a href="/categories/" title="Categories"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-2-line"></use></svg></span><span class="site-state-item-count">2</span></a></div><div class="site-state-item"><a href="/tags/" title="Tags"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="site-state-item-count">9</span></a></div><a class="site-state-item hty-icon-button" href="/" title="文档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-settings-line"></use></svg></span></a></nav><hr style="margin-bottom:0.5rem"><div class="links-of-author"><a class="links-of-author-item hty-icon-button" rel="noopener" title="微信 A18309169837" target="_blank" style="color:orange"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-wechat-2-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="QQ  1197213754" target="_blank" style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://gitee.com/wyb_001" title="GitHub" target="_blank" style="color:#6e5494"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-github-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="E-Mail 1197213754@qq.com" target="_blank" style="color:#8E71C1"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-mail-line"></use></svg></a></div><hr style="margin:0.5rem 1rem"><div class="links"><a class="links-item hty-icon-button" href="/about/" title="关于我" style="color:dodgerblue"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-genderless-line"></use></svg></a></div></div><div class="sidebar-panel sidebar-panel-active" id="post-toc-wrap"><div class="post-toc"><div class="post-toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">简介</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E9%9B%86"><span class="toc-number">2.</span> <span class="toc-text">查询集</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%99%90%E5%88%B6%E6%9F%A5%E8%AF%A2%E9%9B%86"><span class="toc-number">2.1.</span> <span class="toc-text">限制查询集</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E9%9B%86%E7%9A%84%E7%BC%93%E5%AD%98"><span class="toc-number">2.2.</span> <span class="toc-text">查询集的缓存</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%97%E6%AE%B5%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.</span> <span class="toc-text">字段查询</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%AF%94%E8%BE%83%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">3.1.</span> <span class="toc-text">比较运算符</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%81%9A%E5%90%88%E5%87%BD%E6%95%B0"><span class="toc-number">4.</span> <span class="toc-text">聚合函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#F%E5%AF%B9%E8%B1%A1"><span class="toc-number">5.</span> <span class="toc-text">F对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Q%E5%AF%B9%E8%B1%A1"><span class="toc-number">6.</span> <span class="toc-text">Q对象</span></a></li></ol></div></div></div></aside><main class="sidebar-translate" id="content"><div id="post"><article class="post-block" itemscope itemtype="https://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://example.com/2021/01/17/django%20%E6%A8%A1%E5%9E%8B%E6%9F%A5%E8%AF%A2/"><span hidden itemprop="author" itemscope itemtype="https://schema.org/Person"><meta itemprop="name" content="yangbo.wang"><meta itemprop="description"></span><span hidden itemprop="publisher" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="Blog"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">模型查询</h1><div class="post-meta"><div class="post-time" style="display:inline-block"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-line"></use></svg></span> <time title="Created: 2021-01-17 15:12:04" itemprop="dateCreated datePublished" datetime="2021-01-17T15:12:04+08:00">2021-01-17</time></div><div class="post-classify"><span class="post-category"> <span class="post-meta-item-icon" style="margin-right:3px;"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-line"></use></svg></span><span itemprop="about" itemscope itemtype="https://schema.org/Thing"><a class="category" href="/categories/Python/" style="--text-color:var(--hty-text-color)" itemprop="url" rel="index"><span itemprop="text">Python</span></a></span></span><span class="post-tag"><span class="post-meta-divider">-</span><a class="tag" href="/tags/Django/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">Django</span></a><a class="tag" href="/tags/%E6%A8%A1%E5%9E%8B%E6%9F%A5%E8%AF%A2/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">模型查询</span></a><a class="tag" href="/tags/%E6%9F%A5%E8%AF%A2%E9%9B%86/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">查询集</span></a></span></div></div></header><section class="post-body" itemprop="articleBody"><div class="post-content markdown-body" style="--smc-primary:#0078E7;"><h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><ul>
<li>查询集表示从数据库中获取的对象集合  </li>
<li>查询集可以含有零个、一个或多个过滤器  </li>
<li>过滤器基于所给的参数限制查询的结果  </li>
<li>从Sql的角度，查询集和select语句等价，过滤器像where和limit子句  </li>
<li>接下来主要讨论如下知识点  <ul>
<li>查询集  </li>
<li>字段查询：比较运算符，F对象，Q对象  </li>
</ul>
</li>
</ul>
<h3 id="查询集"><a href="#查询集" class="headerlink" title="查询集"></a>查询集</h3><ul>
<li>在管理器上调用过滤器方法会返回查询集  </li>
<li>查询集经过过滤器筛选后返回新的查询集，因此可以写成链式过滤  </li>
<li>惰性执行：创建查询集不会带来任何数据库的访问，直到调用数据时，才会访问数据库  </li>
<li>何时对查询集求值：迭代，序列化，与if合用  </li>
<li>返回查询集的方法，称为过滤器  <ul>
<li>all()  </li>
<li>filter()  </li>
<li>exclude()  </li>
<li>order_by()  </li>
<li>values()：一个对象构成一个字典，然后构成一个列表返回  </li>
</ul>
</li>
<li>写法：  <pre><code>  filter(键1=值1,键2=值2)
  等价于
  filter(键1=值1).filter(键2=值2)</code></pre>
</li>
<li>返回单个值的方法  <ul>
<li>get()：返回单个满足条件的对象  <ul>
<li>如果未找到会引发”模型类.DoesNotExist”异常  </li>
<li>如果多条被返回，会引发”模型类.MultipleObjectsReturned”异常  </li>
</ul>
</li>
<li>count()：返回当前查询的总条数  </li>
<li>first()：返回第一个对象  </li>
<li>last()：返回最后一个对象  </li>
<li>exists()：判断查询集中是否有数据，如果有则返回True  </li>
</ul>
</li>
</ul>
<h4 id="限制查询集"><a href="#限制查询集" class="headerlink" title="限制查询集"></a>限制查询集</h4><ul>
<li>查询集返回列表，可以使用下标的方式进行限制，等同于sql中的limit和offset子句  </li>
<li>注意：不支持负数索引  </li>
<li>使用下标后返回一个新的查询集，不会立即执行查询  </li>
<li>如果获取一个对象，直接使用[0]，等同于[0:1].get()，但是如果没有数据，[0]引发IndexError异常，[0:1].get()引发DoesNotExist异常  </li>
</ul>
<h4 id="查询集的缓存"><a href="#查询集的缓存" class="headerlink" title="查询集的缓存"></a>查询集的缓存</h4><ul>
<li>每个查询集都包含一个缓存来最小* 化对数据库的访问  </li>
<li>在新建的查询集中，缓存为空，首次对查询集求值时，会发生数据库查询，django会将查询的结果存在查询集的缓存中，并返回请求的结果，接下来对查询集求值将重用缓存的结果</li>
<li>情况一：这构成了两个查询集，无法重用缓存，每次查询都会与数据库进行一次交互，增加了数据库的负载  <pre><code>  print([e.title for e in Entry.objects.all()])
  print([e.title for e in Entry.objects.all()])</code></pre>
</li>
<li>情况二：两次循环使用同一个查询集，第二次使用缓存中的数据  <pre><code>  querylist=Entry.objects.all()
  print([e.title for e in querylist])
  print([e.title for e in querylist])</code></pre>
</li>
<li>何时查询集不会被缓存：当只对查询集的部分进行求值时会检查缓存，但是如果这部分不在缓存中，那么接下来查询返回的记录将不会被缓存，这意味着使用索引来限制查询集将不会填充缓存，如果这部分数据已经被缓存，则直接使用缓存中的数据  </li>
</ul>
<h3 id="字段查询"><a href="#字段查询" class="headerlink" title="字段查询"></a>字段查询</h3><ul>
<li>实现where子名，作为方法filter()、exclude()、get()的参数  </li>
<li>语法：属性名称__比较运算符=值  </li>
<li>表示两个下划线，左侧是属性名称，右侧是比较类型  </li>
<li>对于外键，使用“属性名_id”表示外键的原始值  </li>
<li>转义：like语句中使用了%与，匹配数据中的%与，在过滤器中直接写，例如：filter(title__contains=”%”)=&gt;where title like ‘%%%’，表示查找标题中包含%的  </li>
</ul>
<h4 id="比较运算符"><a href="#比较运算符" class="headerlink" title="比较运算符"></a>比较运算符</h4><ul>
<li>exact：表示判等，大小写敏感；如果没有写“ 比较运算符”，表示判等  <pre><code>  filter(isDelete=False)  </code></pre>
</li>
<li>contains：是否包含，大小写敏感<pre><code>  exclude(btitle__contains=&#39;传&#39;)</code></pre>
</li>
<li>startswith、endswith：以value开头或结尾，大小写敏感<pre><code>  exclude(btitle__endswith=&#39;传&#39;)</code></pre>
</li>
<li>isnull、isnotnull：是否为null<pre><code>  filter(btitle__isnull=False)</code></pre>
</li>
<li>在前面加个i表示不区分大小写，如iexact、icontains、istarswith、iendswith  </li>
<li>in：是否包含在范围内  <pre><code>  filter(pk__in=[1, 2, 3, 4, 5])</code></pre>
</li>
<li>gt、gte、lt、lte：大于、大于等于、小于、小于等于  <pre><code>  filter(id__gt=3)</code></pre>
</li>
<li>year、month、day、week_day、hour、minute、second：对日期间类型的属性进行运算  <pre><code>  filter(bpub_date__year=1980)
  filter(bpub_date__gt=date(1980, 12, 31))</code></pre>
</li>
<li>跨关联关系的查询：处理join查询  <ul>
<li>语法：模型类名 &lt;属性名&gt; &lt;比较&gt;  </li>
<li>注：可以没有__&lt;比较&gt;部分，表示等于，结果同inner join  </li>
<li>可返向使用，即在关联的两个模型中都可以使用<br>  filter(heroinfo_ <em>hcontent</em> _contains=’八’)</li>
</ul>
</li>
<li>查询的快捷方式：pk，pk表示primary key，默认的主键是id  <pre><code>  filter(pk__lt=6)  </code></pre>
</li>
</ul>
<h3 id="聚合函数"><a href="#聚合函数" class="headerlink" title="聚合函数"></a>聚合函数</h3><ul>
<li>使用aggregate()函数返回聚合函数的值  </li>
<li>函数：Avg，Count，Max，Min，Sum<pre><code>  from django.db.models import Max
  maxDate = list.aggregate(Max(&#39;bpub_date&#39;))</code></pre>
</li>
<li>count的一般用法：<pre><code>  count = list.count()  </code></pre>
</li>
</ul>
<h3 id="F对象"><a href="#F对象" class="headerlink" title="F对象"></a>F对象</h3><ul>
<li>可以使用模型的字段A与字段B进行比较，如果A写在了等号的左边，则B出现在等号的右边，需要通过F对象构造  <pre><code>  list.filter(bread__gte=F(&#39;bcommet&#39;))</code></pre>
</li>
<li>django支持对F()对象使用算数运算  <pre><code>  list.filter(bread__gte=F(&#39;bcommet&#39;) * 2)</code></pre>
</li>
<li>F()对象中还可以写作“模型类__列名”进行关联查询  <pre><code>  list.filter(isDelete=F(&#39;heroinfo__isDelete&#39;))</code></pre>
</li>
<li>对于date/time字段，可与timedelta()进行运算  <pre><code>  list.filter(bpub_date__lt=F(&#39;bpub_date&#39;) + timedelta(days=1))  </code></pre>
</li>
</ul>
<h3 id="Q对象"><a href="#Q对象" class="headerlink" title="Q对象"></a>Q对象</h3><ul>
<li>过滤器的方法中关键字参数查询，会合并为And进行  </li>
<li>需要进行or查询，使用Q()对象  </li>
<li>Q对象(django.db.models.Q)用于封装一组关键字参数，这些关键字参数与“比较运算符”中的相同  <pre><code>  from django.db.models import Q
  list.filter(Q(pk_ _lt=6))</code></pre>
</li>
<li>Q对象可以使用&amp;（and）、|（or）操作符组合起来  </li>
<li>当操作符应用在两个Q对象时，会产生一个新的Q对象  <pre><code>  list.filter(pk_ _lt=6).filter(bcommet_ _gt=10)
  list.filter(Q(pk_ _lt=6) | Q(bcommet_ _gt=10))</code></pre>
</li>
<li>使用~（not）操作符在Q对象前表示取反<pre><code>  list.filter(~Q(pk__lt=6))</code></pre>
</li>
<li>可以使用&amp;|~结合括号进行分组，构造做生意复杂的Q对象  </li>
<li>过滤器函数可以传递一个或多个Q对象作为位置参数，如果有多个Q对象，这些参数的逻辑为and  </li>
<li>过滤器函数可以混合使用Q对象和关键字参数，所有参数都将and在一起，Q对象必须位于关键字参数的前面  </li>
</ul>
</div><ul class="post-copyright"><li class="post-copyright-author"><strong>Post author: </strong>yangbo.wang</li><li class="post-copyright-link"><strong>Post link: </strong><a href="http://example.com/2021/01/17/django%20%E6%A8%A1%E5%9E%8B%E6%9F%A5%E8%AF%A2/" title="模型查询">http://example.com/2021/01/17/django%20%E6%A8%A1%E5%9E%8B%E6%9F%A5%E8%AF%A2/</a></li><li class="post-copyright-license"><strong>Copyright Notice: </strong>All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener" title="CC BY-NC-SA 4.0 "><svg class="icon"><use xlink:href="#icon-creative-commons-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-by-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-nc-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-sa-line"></use></svg></a> unless otherwise stated.</li></ul></section></article><div class="post-nav"><div class="post-nav-item"><a class="post-nav-prev" href="/2021/01/17/django%E8%A7%86%E5%9B%BE/" rel="prev" title="Django视图简介"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-left-s-line"></use></svg><span class="post-nav-text">Django视图简介</span></a></div><div class="post-nav-item"><a class="post-nav-next" href="/2021/01/17/Django%E6%A8%A1%E5%9E%8B/" rel="next" title="ORM简介"><span class="post-nav-text">ORM简介</span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-right-s-line"></use></svg></a></div></div></div></main><footer class="sidebar-translate" id="footer"><div class="copyright"><span>&copy; 2019 – 2021 </span><span class="with-love" id="animate"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-cloud-line"></use></svg></span><span class="author"> yangbo.wang</span></div><div class="powered"><span>Powered by <a href="https://hexo.io" target="_blank" rel="noopener">Hexo</a> v5.3.0</span><span class="footer-separator">|</span><span>Theme - <a rel="noopener" href="https://github.com/YunYouJun/hexo-theme-yun" target="_blank"><span>Yun</span></a> v1.4.0</span></div></footer><a class="hty-icon-button" id="goUp" aria-label="back-to-top" href="#"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-up-s-line"></use></svg><svg class="progress-circle-container" viewBox="0 0 100 100"><circle class="progress-circle" id="progressCircle" cx="50" cy="50" r="48" fill="none" stroke="#0078E7" stroke-width="2" stroke-linecap="round"></circle></svg></a></div></body></html>